use std::io::{Write, Read};
use std::fs;
use std::process::exit;

fn main() {
    let mut args = std::env::args();

    if args.len() < 2 {
        eprintln!("error: At least one parameter.");
        exit(-1);
    }

    args.next();
    let mut files = Vec::<fs::File>::new();
    let mut paths = Vec::<String>::new();
    for arg in args {
        let res_file = fs::OpenOptions::new()
            .read(true).write(true).open(&arg);
        match res_file {
            Ok(file) => {
                files.push(file);
                paths.push(arg);
            },
            Err(_) => {
                eprintln!("error: File \'{}\' is not accessible.", &arg);
                exit(-1);
            }
        }
    }

    let mut ct: usize = 0;
    for mut file in files {
        let path = paths.get(ct).unwrap();
        ct += 1;
        let mut flag = 0;
        let mut buf = [0_u8];
        let mut buf2 = Vec::<u8>::new();
        loop {
            let size = file.read(&mut buf).unwrap();
            if size == 0 { break; }
            let b = buf[0];
            if b == b'\r' {
                flag = 1;
                buf2.push(b'\n');
            }
            else if flag == 1 {
                flag = 0;
                if b == b'\n' {
                    continue;
                }
                else {
                    buf2.push(b);
                }
            }
            else {
                buf2.push(b);
            }
        }
        let mut of = fs::File::create(path).unwrap();
        let result = of.write_all(buf2.as_slice());
        if let Err(_) = result {
            eprintln!("error: File \'{}\' is not accessible.", path);
            exit(-1);
        }
    }
}
